package br.com.k19.managedBeans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.k19.models.Carro;
import br.com.k19.sessionBeans.CarroSessionBean;

@ManagedBean
public class CarroManagedBean {
	
	private CarroSessionBean carroSessionBean;
	private Carro carro = new Carro();
	private List<Carro> carros;
	
	public CarroManagedBean() {
		System.err.println("Calling constructor: class: CarroManagedBean");
	}

	public Carro getCarro() {
		return carro;
	}

	public void setCarro(Carro carro) {
		this.carro = carro;
	}
	
	public void adicionarCarro(){
		carroSessionBean = new CarroSessionBean(getEntityManager());
		carroSessionBean.adicionar(carro);
		this.carros = null;
	}
	
	public List<Carro> getCarros(){
		if (this.carros == null) {
			carroSessionBean = new CarroSessionBean(getEntityManager());
			System.out.println("Calling repository: Class: CarroManagedBean");
			this.carros = carroSessionBean.consultarTodos();
		}
		return carros;
	}
	
	private EntityManager getEntityManager(){
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
		return (EntityManager) request.getAttribute("entityManager");
	}
}
